package com.nowcoder.community.dao.impl;

import com.nowcoder.community.dao.EntityFollowDao;
import com.nowcoder.community.util.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Component
public class EntityFollowDaoRedisImpl implements EntityFollowDao {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public void followUser(int followerId, int userId) {
        long now = System.currentTimeMillis();
        // 为follower的已关注列表中添加user
        redisTemplate.opsForZSet().add(RedisKeyUtils.getUserFollowZSetKey(followerId), userId, now);

        // 为user的被关注列表中添加follower
        redisTemplate.opsForZSet().add(RedisKeyUtils.getUserFollowerZSetKey(userId), followerId, now);
    }

    @Override
    public void unfollowUser(int followerId, int userId) {
        // 移除follower的已关注列表user
        redisTemplate.opsForZSet().remove(RedisKeyUtils.getUserFollowZSetKey(followerId), userId);

        // 移除user的被关注列表follower
        redisTemplate.opsForZSet().remove(RedisKeyUtils.getUserFollowerZSetKey(userId), followerId);
    }

    @Override
    public int countFollower(int userId) {
        String key = RedisKeyUtils.getUserFollowerZSetKey(userId);
        Long ret = redisTemplate.opsForZSet().size(key);
        if (ret != null) {
            return ret.intValue();
        }
        return 0;
    }

    @Override
    public int countFollow(int userId) {
        String key = RedisKeyUtils.getUserFollowZSetKey(userId);
        Long ret = redisTemplate.opsForZSet().size(key);
        if (ret != null) {
            return ret.intValue();
        }
        return 0;
    }

    @Override
    public boolean isFollow(int followerId, int userId) {
        String key = RedisKeyUtils.getUserFollowerZSetKey(userId);
        Double ret = redisTemplate.opsForZSet().score(key, followerId);
        return ret != null;
    }
}
